<template>
  <div class="login-wrapper">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <span>用户登录</span>
        </div>
      </template>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        label-width="60px"
        @keyup.enter="handleLogin"
      >
        <!-- 用户名 -->
        <el-form-item label="账号" prop="userName">
          <el-input
            v-model="loginForm.userName"
            placeholder="请输入用户名"
            prefix-icon="User"
            clearable
          />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%"
            :loading="loading"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import API from '../utils/api'
import router from '../router';
import {useGlobalStore} from '../store/userInfo'

// 表单引用
const loginFormRef = ref()

// 表单数据
const loginForm = reactive({
  userName: 'admin',
  password: 'admin'
})

// 校验规则
const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
  ]
}

// 登录状态
const loading = ref(false)

// 登录方法
const handleLogin = () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      // 模拟登录请求
	  let result = await API.login(loginForm).then(res=>{
		ElMessage.success('登录成功！')
      	loading.value = false
		const globalData = useGlobalStore();
		globalData.token= res
		router.push('/')
	  }).catch(err=>{
		loading.value = false
	  })
      
    } else {
      ElMessage.error('用户名或密码错误')
    }
  })
}
</script>

<style scoped>
.login-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #83a4d4, #b6fbff);
}

.login-card {
  width: 400px;
  padding: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}
</style>